package com.spic.business.train.createtest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.spic.business.common.datascope.anotation.BusinessDataScope;
import com.spic.business.train.createtest.domain.TrainExam;
import com.spic.business.train.createtest.mapper.TrainExamMapper;
import com.spic.business.train.createtest.service.ITrainExamService;
import com.spic.business.train.examDetail.domain.TrainExamDetail;
import com.spic.business.train.examDetail.service.ITrainExamDetailService;
import com.spic.business.train.examination.domain.TrainPaper;
import com.spic.business.train.examination.mapper.TrainPaperMapper;
import com.spic.business.train.prepare.domain.TrainExamUserState;
import com.spic.business.train.prepare.mapper.TrainExamUserStateMapper;
import com.spic.business.train.prepare.service.ITrainPrepareService;
import com.spic.business.train.questions.domain.TrainQuestions;
import com.spic.business.train.questions.mapper.TrainQuestionsMapper;
import com.spic.business.train.trainInfo.service.ITrainInfoService;
import com.spic.business.train.trainUser.domain.TrainUser;
import com.spic.business.train.trainUser.mapper.TrainUserMapper;
import com.spic.business.train.trainUserAnswer.domain.TrainUserAnswer;
import com.spic.business.train.trainUserAnswer.mapper.TrainUserAnswerMapper;
import com.spic.common.core.utils.DateUtils;
import com.spic.common.core.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 创建考试Service业务层处理
 *
 * @author qishaoping
 * @date 2021-10-21
 */
@Service
public class TrainExamServiceImpl extends ServiceImpl<TrainExamMapper,TrainExam>  implements ITrainExamService
{
    @Autowired
    private TrainExamMapper trainExamMapper;
    @Autowired
   private TrainQuestionsMapper trainQuestionsMapper;
    @Autowired
    private TrainPaperMapper trainPaperMapper;
    @Autowired
    private TrainUserMapper trainUserMapper;
    @Autowired
    private ITrainInfoService iTrainInfoService;
    @Autowired
    private TrainUserAnswerMapper trainUserAnswerMapper;
    @Autowired
    private TrainExamUserStateMapper trainExamUserStateMapper;
    @Autowired
    private ITrainPrepareService trainPrepareService;
    @Autowired
    private ITrainExamDetailService trainExamDetailService;

    /**
     * 查询创建考试
     *
     * @param id 创建考试主键
     * @return 创建考试
     */
    @Override
    public TrainExam selectTrainExamById(Long id)
    {
        return trainExamMapper.selectTrainExamById(id);
    }

    @Override
    public List<TrainExam> selectTrainExamByIds(Long id) {
        return trainExamMapper.selectTrainExamByIds(id);
    }

    /**
     * 查询创建考试列表
     *
     * @param trainExam 创建考试
     * @return 创建考试
     */
    @Override
    @BusinessDataScope(menuPath = "business/train/createtest/index")
    public List<TrainExam> selectTrainExamList(TrainExam trainExam)
    {
        return trainExamMapper.selectTrainExamList(trainExam);
    }

    @Override
    public List<TrainExam> selectTrainExamListNoDataScope(TrainExam trainExam)
    {
        return trainExamMapper.selectTrainExamList(trainExam);
    }

    /**
     * 新增创建考试
     *
     * @param trainExam 创建考试
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertTrainExam(TrainExam trainExam) {
        //新增
        trainExam.setState(0L);
        trainExam.setCreateTime(DateUtils.getNowDate());
        //计算试题总数
        int radioEasy = trainExam.getEasyRadioCount();
        int radioMid = trainExam.getMidRadioCount();
        int radioDif = trainExam.getDifRadioCount();
        int mutiEasy = trainExam.getEasyMultiCount();
        int mutiMid = trainExam.getMidMultiCount();
        int mutiDif = trainExam.getDifMultiCount();
        int judgeEasy = trainExam.getEasyJudgeCount();
        int judgeMid = trainExam.getMidJudgeCount();
        int judgeDif = trainExam.getDifJudgeCount();
        int gapEasy = trainExam.getEasyGapCount();
        int gapDif = trainExam.getDifGapCount();
        int gapMid = trainExam.getMidGapCount();

        List<List<Integer>> lists = Lists.newArrayList(Lists.newArrayList(radioDif,radioMid, radioEasy),
                Lists.newArrayList(mutiDif,mutiMid, mutiEasy),
                Lists.newArrayList(judgeDif,judgeMid, judgeEasy),
                Lists.newArrayList(gapDif,gapMid, gapEasy));
        trainExam.setQuestionsNumber(radioEasy + radioMid + radioDif + mutiEasy + mutiMid + mutiDif + judgeEasy + judgeMid + judgeDif + gapEasy + gapDif + gapMid);
        Map<Integer, String> sorceMap = ImmutableMap.<Integer, String>builder()
                .put(1,trainExam.getRadionScore())
                .put(2,trainExam.getMultiScore())
                .put(3,trainExam.getJudgeScore())
                .put(4,trainExam.getGapScore())
                .build();
        //判断当前题库中对应类型和难度的题是否满足
        for (int i = 1; i <= lists.size(); i++)
        {
            List<Integer> item = lists.get(i -1);
            for (int j = 1; j <= item.size(); j++)
            {
                int count = trainQuestionsMapper.typeCount(i, j, trainExam.getTestClassification());
                if (item.get(j -1) > count)
                {
                    throw new RuntimeException("试题数量不足。");
                }
            }
        }
        //新增试卷规则
        trainExamMapper.insertTrainExam(trainExam);
        /**
         *  1.根据培训查询对应用户
         *  2.根据培训用户遍历
         *  3.给每个培训用户 创建试卷
         */
        TrainUser tUser = new TrainUser();
        tUser.setTrainInfoId(trainExam.getTrainId());
        List<TrainUser> uList = trainUserMapper.selectTrainUserList(tUser);
        if(uList!=null && uList.size()>0){
            for (TrainUser user : uList)
            {
                Long userId = user.getUserId();
                int sort = 1;
                for (int i = 1; i <= lists.size(); i++)
                {
                    List<Integer> item = lists.get(i - 1);
                    for (int j = 1; j <= item.size(); j++)
                    {
                        List<TrainQuestions> quList = trainQuestionsMapper.listByRandom(String.valueOf(j), item.get(j - 1), trainExam.getTestClassification(), String.valueOf(i));

                        for (TrainQuestions qu : quList) {
                            TrainPaper trainPaper = new TrainPaper();
                            String live = sorceMap.get(i);
                            Double lives = Double.parseDouble(live);
                            trainPaper.setFraction(lives);
                            trainPaper.setExamId(trainExam.getId());
                            trainPaper.setQuestionsId(qu.getId());
                            trainPaper.setSort(sort + "");
                            sort++;
                            trainPaper.setQuType(qu.getQuestionsType());
                            trainPaper.setUserId(userId);//培训用户id
                            trainPaperMapper.insertTrainPaper(trainPaper);
                        }
                    }
                }
            }
        }

        //新增试题后把对应的考试用户查询出来  放到临时表中
        TrainUser trainUser = new TrainUser();
        trainUser.setTrainInfoId(trainExam.getTrainId());
        List<TrainUser> trainUserList = trainUserMapper.selectTrainUserList(trainUser);
        if(trainUserList!=null && trainUserList.size()>0){
            for (TrainUser user : trainUserList)
            {
                TrainExamUserState trainExamUserState = new TrainExamUserState();
                trainExamUserState.setExamId(trainExam.getId());
                trainExamUserState.setTrainUserId(user.getUserId());
                trainExamUserStateMapper.insert(trainExamUserState);
            }
        }
        return trainExam.getId().intValue();
    }

    /**
     * 修改创建考试
     *
     * @param trainExam 创建考试
     * @return 结果
     */
    @Override
    public int updateTrainExam(TrainExam trainExam)
    {
        return 0;
    }


    /**
     * 考试结束
     * 1.更新考试信息
     * 2.更新培训信息
     * 3.培训结束
     * @author yangjie
     * @param trainExam 考试信息
     */
    @Transactional
    @Override
    public int updateTrainExamAndTrainInfo(TrainExam trainExam)
    {

        Long userId = SecurityUtils.getUserId();
        Long examId = trainExam.getId();
        TrainExam trainExamnew = trainExamMapper.selectTrainExamById(examId);
        int sucessCount = 0;
        trainExam.setUpdateTime(DateUtils.getNowDate());
        String trainId = trainExamnew.getTrainId();
        double passingScore = Double.parseDouble(trainExamnew.getPassingScore());//及格分
        //计算实际得分
        TrainPaper trainPaper = new TrainPaper();
        trainPaper.setExamId(examId);
        trainPaper.setUserId(userId);
        List<TrainPaper> trainPaperList = trainPaperMapper.selectTrainPaperList(trainPaper);
        double totalScore = 0d;
        for (TrainPaper paper : trainPaperList)
        {
            Long paperId = paper.getId();
            TrainUserAnswer userAnswer = new TrainUserAnswer();
            userAnswer.setUserId(userId);
            userAnswer.setPaperId(paperId+"");
            List<TrainUserAnswer> userAnswersList = trainUserAnswerMapper.selectTrainUserAnswerList(userAnswer);
            if(userAnswersList!=null&& userAnswersList.size()>0){
                TrainUserAnswer trainUserAnswer = userAnswersList.get(0);
                trainUserAnswer.setActualTime(trainExam.getActualTime());
                trainUserAnswerMapper.updateTrainUserAnswer(trainUserAnswer);
                totalScore += trainUserAnswer.getActualScore();
            }
        }
        TrainUser trainUser = new TrainUser();
        trainUser.setTrainInfoId(trainId+"");
        trainUser.setUserId(userId);
        List<TrainUser> trainUserList = trainUserMapper.selectTrainUserList(trainUser);
        if(trainUserList!=null && trainUserList.size()>0)
        {
            TrainUser trainUserUpdate = trainUserList.get(0);
            TrainUser trainUserByid = trainUserMapper.selectTrainUserById(trainUserUpdate.getId());
            trainUserByid.setStateFinished();
            // 0 培训合格 1培训不合格
            if(totalScore>=passingScore){
                trainUserByid.setJudge("0");
            }else{
                trainUserByid.setJudge("1");
            }
            int userCount = trainUserMapper.updateTrainUser(trainUserByid);
            sucessCount = sucessCount+userCount;
        }
        /** 0 培训未完成  1 培训完成 */
        Boolean finshflag = false;
        TrainUser trainUserState = new TrainUser();
        trainUserState.setTrainInfoId(trainId+"");
        List<TrainUser> trainUserListState = trainUserMapper.selectTrainUserList(trainUserState);
        if(trainUserListState!=null && trainUserListState.size()>0){
            for (TrainUser user : trainUserListState)
            {
                Integer trainState = user.getTrainState();
                if(trainState==1){
                    finshflag = true;
                }else{
                    finshflag = false;
                    break;
                }
            }
            if(finshflag){
                trainExam.setState(1L);
            }
        }
        int examCount = trainExamMapper.updateTrainExam(trainExam);
        sucessCount = sucessCount+examCount;

        //每个人培训结束
        iTrainInfoService.updateTrainInfoforUserTrainEnd(trainId+"");
        //更新考试临时表状态 为考完
        QueryWrapper<TrainExamUserState> sectionQueryWrapper = new QueryWrapper<>();
        sectionQueryWrapper.eq("train_user_id",SecurityUtils.getUserId());
        sectionQueryWrapper.eq("exam_id",trainExam.getId());
        List<TrainExamUserState> trainExamUserStates = trainExamUserStateMapper.selectList(sectionQueryWrapper);
        if(trainExamUserStates!=null && trainExamUserStates.size()>0){
            TrainExamUserState trainExamUserState = new TrainExamUserState();
            trainExamUserState.setId(trainExamUserStates.get(0).getId());
            trainExamUserState.setStates("1");
            trainExamUserStateMapper.updateById(trainExamUserState);
        }

        //生成考试详情 每个人对应一条记录
        TrainExamDetail trainExamDetail = new TrainExamDetail();
        trainExamDetail.setTitle(trainExamnew.getTitle());
        trainExamDetail.setContent(trainExamnew.getContent());
        trainExamDetail.setDuration(trainExamnew.getDuration());
        trainExamDetail.setExamId(examId);
        trainExamDetail.setPassingScore(trainExamnew.getPassingScore());
        trainExamDetail.setFraction(trainExamnew.getFraction());
        trainExamDetail.setQuestionsNumber(trainExamnew.getQuestionsNumber());
        trainExamDetail.setScore(totalScore);
        trainExamDetail.setUserId(SecurityUtils.getUserId()+"");
        trainExamDetail.setDeptId(Long.valueOf(SecurityUtils.getDeptId()));
        trainExamDetail.setCreateBy(SecurityUtils.getUserId()+"");
        trainExamDetailService.insertTrainExamDetail(trainExamDetail);

        return sucessCount;
    }

    /**
     * 批量删除创建考试
     *
     * @param ids 需要删除的创建考试主键
     * @return 结果
     */
    @Override
    public int deleteTrainExamByIds(Long[] ids)
    {
        return trainExamMapper.deleteTrainExamByIds(ids);
    }

    /**
     * 删除创建考试信息
     *
     * @param id 创建考试主键
     * @return 结果
     */
    @Override
    public int deleteTrainExamById(Long id)
    {
        return trainExamMapper.deleteTrainExamById(id);
    }

    @Override
    public List<TrainExam> selectTrainExamListByUser(TrainExam trainExam)
    {
        Long loginuserId = SecurityUtils.getUserId();
        List<TrainExam> trainExamsList = trainExamMapper.selectTrainExamListByUser(trainExam);
        List<TrainExam> trainExamsListNew = new ArrayList<>();
        if(trainExamsList!=null && trainExamsList.size()>0){
            for (TrainExam exam : trainExamsList)
            {
                String trainId = exam.getTrainId();
                TrainUser trainUser = new TrainUser();
                trainUser.setTrainInfoId(trainId+"");
                trainUser.setUserId(loginuserId);
                List<TrainUser> trainUsersList = trainUserMapper.selectTrainUserList(trainUser);
                if(trainUsersList!=null && trainUsersList.size()>0){
                    TrainExamUserState trainExamUserState = trainPrepareService.trainExamUserStateByFinsh(exam.getId(),loginuserId);
                    exam.setState(Long.valueOf(trainExamUserState.getStates()));
                    trainExamsListNew.add(exam);
                }
            }
        }
        return trainExamsListNew;
    }


}
